<?php

require_once 'objects/person.php';
require_once 'objects/Preceba.php';
require_once 'objects/Predeste.php';
require_once 'objects/Ceba.php';
require_once 'conexion.php';

class login {

    private $conx;
    private $sql0 = "SELECT * FROM person WHERE mail = '%s' and passwd = '%s' and rolcod = 00;";
    private $sql1 = "SELECT * FROM person WHERE mail = '%s' and passwd = '%s' and rolcod = 01;";

    public function __construct() {
        $this->conx = null;
    }
    
    public function login($mail, $pswd) {
        session_start();
        if (isset($_SESSION['user'])) {
            session_destroy();
        }

        $consult_0 = sprintf($this->sql0, $mail, $pswd);
        $consult_1 = sprintf($this->sql1, $mail, $pswd);
        
        $this->conx = new conexion();
        $result_0 = pg_query($this->conx->getConexionDB(), $consult_0);
        $result_1 = pg_query($this->conx->getConexionDB(), $consult_1);
        
        $this->conx->closeConexionDB();
        $this->conx = null;
        $fila_0 = pg_fetch_array($result_0);
        $fila_1 = pg_fetch_array($result_1);
        $predeste=new Predeste();
        $preceba=new preceba();
        $ceba=new Ceba();
        $_SESSION['predeste1'] = $predeste;
        $_SESSION['predeste2'] = $predeste;
        $_SESSION['predeste3'] = $predeste;
        $_SESSION['preceba1'] = $preceba;
        $_SESSION['preceba2'] = $preceba;
        $_SESSION['preceba3'] = $preceba;
        $_SESSION['ceba1'] = $ceba;
        $_SESSION['ceba2'] = $ceba;
        $_SESSION['ceba3'] = $ceba;
        if ($fila_0) {
            $pers = new person();
            $pers->setNameuser($fila_0['nameperson']);
            $pers->setMail($fila_0['mail']);
            $pers->setDocnum($fila_0['docnum']);
            $pers->setRolperson($fila_0['rolcod']);
            $pers->setLastname($fila_0['lastname']);
            $_SESSION['user'] = $pers;
            header("location: adm/menuadm.php");
        } else if ($fila_1) {
            $per = new person();
            $per->setNameuser($fila_1['nameperson']);
            $per->setMail($fila_1['mail']);
            $per->setDocnum($fila_1['docnum']);
            $per->setRolperson($fila_1['rolcod']);
            $per->setLastname($fila_1['lastname']);
            $per->setAddress($fila_1['address']);
            $per->setPhone($fila_1['phone']);
            $_SESSION['user'] = $per;
            header("location: user/menuUser.php");
        } else {
            header("location: ../");
        }
    }

}

?>
